package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.external.ExternalInterface;
	import flash.net.Socket;
	import flash.system.System;

	public class WebSocket extends Sprite{
		private var socket:Socket;
		private var isOpen:Boolean = false;
		private var eventMap = {"onIOError":"","onSocketData":"","onClose":"","onConnect":""};

		public function WebSocket(){
			socketInit();
		}
		
		//socket初始化
		public function socketInit():void{
			flash.system.System.useCodePage = true;
			
			flash.external.ExternalInterface.addCallback("addEvent",socketAddEvent);
			flash.external.ExternalInterface.addCallback("open",socketStart);
			flash.external.ExternalInterface.addCallback("close",socketClose);
			flash.external.ExternalInterface.addCallback("isOpen",socketIsOpen);
			flash.external.ExternalInterface.addCallback("sendData",onSendData);
		}
		
		public function socketClose(){
			this.socket.close();
			this.isOpen = false;
		}
		
		//注册socket事件
		public function socketAddEvent(eventName:String, funName:String){
			eventMap[eventName] = funName;
		}
		
		//是否是打开的
		public function socketIsOpen(){
			return isOpen;
		}
		
		public function socketStart(host:String , port:int){
			socket = new Socket();
			socket.addEventListener(Event.CONNECT , onConnect);
			socket.addEventListener(Event.CLOSE, onClose);
			socket.addEventListener(ProgressEvent.SOCKET_DATA , onSocketData);
			socket.addEventListener(IOErrorEvent.IO_ERROR , onIOError); 
			socket.connect(host, port);	
		}
		
		
		
		//连接成功
		public function onConnect(myStatus:Event):void{
			socket.writeUTFBytes("<policy-file-xxquest/>\n");
			socket.flush();
			isOpen = true;
			if(eventMap["onConnect"]!=null && eventMap["onConnect"]!=""){
				flash.external.ExternalInterface.call(eventMap["onConnect"]);
			}
		}
		
		//服务器关闭
		internal function onClose(myStatus:Event):void{
			isOpen = false;
			if(eventMap["onClose"]!=null && eventMap["onClose"]!=""){
				flash.external.ExternalInterface.call(eventMap["onClose"]);
			}
		}
		
		//接收服务器发送数据
		internal function onSocketData(myStatus:Event):void{
			var msg:String = socket.readUTFBytes(socket.bytesAvailable);
			if(eventMap["onSocketData"]!=null && eventMap["onSocketData"]!=""){
				flash.external.ExternalInterface.call(eventMap["onSocketData"], msg);
			}
		}
		
		//向服务器发送数据
		internal function onSendData(msg:String):void{
			socket.writeUTFBytes(msg+"\n");
			socket.flush();
		}
		
		//通讯流异常
		internal function onIOError(myStatus:Event):void{
			isOpen = false;
			if(eventMap["onIOError"]!=null && eventMap["onIOError"]!=""){
				flash.external.ExternalInterface.call(eventMap["onIOError"]);
			}
		}
	}
}
